package com.autoagent.ai_live_master.webSocket.service;

import com.autoagent.ai_live_master.webSocket.config.PuppeteerProperties;
import io.github.bonigarcia.wdm.WebDriverManager;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.stereotype.Service;

import java.time.Duration;

@Slf4j
@Service
public class PuppeteerService {
    private final PuppeteerProperties puppeteerProperties;
    private WebDriver driver;
    private static final String VUE_APP_URL = "http://localhost:5173/";

    public PuppeteerService(PuppeteerProperties puppeteerProperties) {
        this.puppeteerProperties = puppeteerProperties;
    }

    public void connect(String roomNumber) {
        try {
            initializeDriver();
            log.info("正在打开Vue应用页面: {}", VUE_APP_URL);
            driver.get(VUE_APP_URL);
            
            // 等待页面加载
            WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(20));
            
            // 等待页面完全加载
            wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(".puppeteer-area")));
            Thread.sleep(2000);
            
            // 输入房间号
            log.info("正在输入房间号: {}", roomNumber);
            WebElement roomInput = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#puppeteer-room-input")));
            roomInput.clear();
            Thread.sleep(500);
            roomInput.sendKeys(roomNumber);
            Thread.sleep(500);
            
            // 点击连接按钮
            log.info("正在点击连接按钮");
            WebElement connectButton = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#puppeteer-connect-btn")));
            connectButton.click();
            
            // 等待连接成功
            Thread.sleep(3000);
            String wssUrl = puppeteerProperties.getWsBaseUrl() + roomNumber;
            
            // 输入WSS地址
            log.info("正在输入WSS地址: {}", wssUrl);
            WebElement relayInput = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#puppeteer-wss-input")));
            relayInput.clear();
            Thread.sleep(500);
            relayInput.sendKeys(wssUrl);
            Thread.sleep(500);
            
            // 点击转发按钮
            log.info("正在点击转发按钮");
            WebElement relayButton = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#puppeteer-relay-btn")));
            relayButton.click();
            
            log.info("操作完成");
        } catch (Exception e) {
            log.error("Puppeteer操作失败", e);
            if (driver != null) {
                try {
                    driver.quit();
                } catch (Exception ex) {
                    log.error("关闭浏览器失败", ex);
                }
                driver = null;
            }
            throw new RuntimeException("Puppeteer操作失败: " + e.getMessage());
        }
    }

    public void disconnect() {
        try {
            if (driver != null) {
                log.info("正在关闭浏览器");
                driver.quit();
                driver = null;
            }
        } catch (Exception e) {
            log.error("关闭浏览器失败", e);
            throw new RuntimeException("关闭浏览器失败: " + e.getMessage());
        }
    }

    private void initializeDriver() {
        if (driver == null) {
            log.info("正在初始化Chrome浏览器");

            try {
                // 使用WebDriverManager自动管理驱动版本
                WebDriverManager.chromedriver().setup();
                
                ChromeOptions options = new ChromeOptions();
                
                // 如果有指定Chrome路径，则使用
                if (puppeteerProperties.getChromePath() != null && !puppeteerProperties.getChromePath().isEmpty()) {
                    options.setBinary(puppeteerProperties.getChromePath());
                }
                
                options.addArguments("--headless");
                options.addArguments("--no-sandbox");
                options.addArguments("--disable-dev-shm-usage");
                options.addArguments("--disable-gpu");
                options.addArguments("--window-size=1920,1080");
                options.addArguments("--disable-extensions");
                options.addArguments("--disable-plugins");
                options.addArguments("--disable-images");
                options.addArguments("--disable-javascript");
                
                // 添加稳定性选项
                options.addArguments("--disable-blink-features=AutomationControlled");
                options.setExperimentalOption("useAutomationExtension", false);
                options.setExperimentalOption("excludeSwitches", new String[]{"enable-automation"});
                
                driver = new ChromeDriver(options);
                
            } catch (Exception e) {
                log.error("WebDriverManager初始化失败，尝试使用手动配置", e);
                
                // 回退到手动配置
                if (puppeteerProperties.getChromeDriver() != null) {
                    System.setProperty("webdriver.chrome.driver", puppeteerProperties.getChromeDriver());
                }
                
                ChromeOptions options = new ChromeOptions();
                if (puppeteerProperties.getChromePath() != null && !puppeteerProperties.getChromePath().isEmpty()) {
                    options.setBinary(puppeteerProperties.getChromePath());
                }
                
                options.addArguments("--headless");
                options.addArguments("--no-sandbox");
                options.addArguments("--disable-dev-shm-usage");
                options.addArguments("--window-size=1920,1080");
                
                driver = new ChromeDriver(options);
            }
        }
    }
}